/*

*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "ch.h"
#include "hal.h"

#include "shell.h"
#include "chprintf.h"

#include "myMisc.h"
#include "myUSB.h"
#include "myNRF24.h"

#ifndef TARGET_SENDER
#include "myPWM.h"
#endif

#include "myADC.h"
#include "remote.h"

void initExt(void);
/*===========================================================================*/
/* Generic code.                                                             */
/*===========================================================================*/

/*
 * assert Shell Commands to functions
 */

static const ShellCommand commands[] = {
  {"mem", cmd_mem},
  {"threads", cmd_threads},
  {"toggle", cmd_toggle},
  {"t", cmd_toggle},
  {"blinkspeed", cmd_blinkspeed},
  {"bs", cmd_blinkspeed},
	{"nrf", cmd_nrf_check},
	{"nw", cmd_nrf_wr},
#ifndef TARGET_SENDER
  {"pwm", cmd_pwm},
#endif
  {"readContinuousData", cmd_measureRead},
  {"r", cmd_measureRead},
  {NULL, NULL}
};


/*
 * Shell configuration
 */

#define SHELL_WA_SIZE   THD_WA_SIZE(2048)

static const ShellConfig shell_cfg1 = {
  (BaseSequentialStream *)&SDU1,
  commands
};

/*
 * Application entry point.
 */
int main(void) {
  /*
   * Shell thread
   */
  Thread *shelltp = NULL;
	
  /*
   * System initializations.
   * - HAL initialization, this also initializes the configured device drivers
   *   and performs the board-specific initializations.
   * - Kernel initialization, the main() function becomes a thread and the
   *   RTOS is active.
   */
  halInit();
  chSysInit();

	initExt();
#ifndef TARGET_SENDER
	initPWM();
#endif
	myADCinit();
	startNRF24();
	myUSBinit();

	
  /*
   * Creates the blinker thread.
   */
  startBlinker();

  /*
   * Creates the control thread.
   */
  startRemote();
	

  /*
   * Main loop, does nothing except spawn a shell when the old one was terminated
   */
  while (TRUE) {
    if (!shelltp && isUsbActive())
      {
        shelltp = shellCreate(&shell_cfg1, SHELL_WA_SIZE, NORMALPRIO);
      }
    else if (chThdTerminated(shelltp)) {
      chThdRelease(shelltp);    /* Recovers memory of the previous shell.   */
      shelltp = NULL;           /* Triggers spawning of a new shell.        */
    }
    chThdSleepMilliseconds(1000);  }
}
